﻿using System.Linq.Extensions;
using System.Linq.PageList;
using Dyao.Book.Contract;
using Dyao.Book.Entity;
using Dyao.Book.Repository.Abstractions;
using Foundation.Core;

namespace Dyao.Book.Repository
{
    using Foundation.Replacement;

    public class ChapterMgrRepository : DataRepository<BookCatalogueEntity, string>, IChapterMgrRepository
    {
        /// <inheritdoc cref="IChapterMgrRepository.GetPageListAsync"/>
        public async Task<IPageList<BookCatalogueEntity>> GetPageListAsync(IPageFilter<ChapterFilterDto> pageFilter, CancellationToken cancellationToken = default)
        {
            var filter = pageFilter.Filter ?? new ChapterFilterDto();
            var query = this.GetQueryable()
                .Where(b => b.BookId == filter.BookId)
                .WhereIf(b => b.CatalogueName.Contains(filter.ChapterName), !filter.ChapterName.IsNullOrEmpty())
                .WhereIf(b => b.CrawlComplete == filter.CrawlComplete.Value, filter.CrawlComplete.HasValue)
                .WhereIf(b => b.IsMatchSource == filter.MatchSource.Value, filter.MatchSource.HasValue)
                .OrderOrThenBy(x => x.ID, true)
                .AsNoTracking();

            return await query.ToPageListAsync(pageFilter, cancellationToken);
        }
    }
}
